import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:gameplay_flutter/lib_basemodel/country/country_model.dart';
import 'package:gameplay_flutter/lib_baseview/utils/cache_util.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:gameplay_flutter/lib_network/http_api.dart';
import 'package:gameplay_flutter/lib_network/http_helper.dart';
import 'package:gameplay_flutter/lib_user/user_manager.dart';
import 'package:gameplay_flutter/m_me/me_api.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../lib_basemodel/user/user.dart';
import 'model/lable_model.dart';

class MeController extends GetxController {
  var languageCode = CacheUtil.get(CacheKeys.languageCode).obs;

  var user = User().obs;
  var countryList = <CountryModel>[].obs;
  var tagList = <LableModel>[].obs;

  @override
  void onInit() {
    super.onInit();
    getUserMine();
    // getUserMine();
  }

  // 更新 languageCode 的方法
  void updateLanguageCode(String code) {
    ImAPI.giftList();
    languageCode.value = code;
  }

  getUserMine({String userId = ""}) async {
    var uId = userId.isNotEmpty
        ? userId
        : UserManager.instance.currentUser?.id?.toString() ?? "0";
    var res = await HttpHelper.instance().post(
      MeApi.userMine,
      body: {"userId": uId},
      showLoading: false,
      showToast: true,
    );
    if (res.result is Map<String, dynamic> &&
        res.result['userInfo'] is Map<String, dynamic>) {
      User details = User.fromJson(res.result['userInfo']);
      debugPrint("getUserDetails userInfo: ${res.result['userInfo']}");
      user.value = details;
    } else {
      debugPrint("res.result 不是有效的 JSON 数据");
    }
  }

  getUserDetails1() async {
    var uId = UserManager.instance.currentUser?.id?.toString() ?? "0";
    var res = await HttpHelper.instance().post(
      MeApi.userDetail,
      body: {"userId": uId},
      showLoading: true,
      showToast: true,
    );
    if (res.result is Map<String, dynamic>) {
      User details = User.fromJson(res.result);
      user.update((val) {
        val?.country = details.country;
        val?.aboutList = details.aboutList;
        val?.about = details.about;
        val?.myVoice = details.myVoice;
        val?.duration = details.duration;
        val?.nickname = details.nickname;
        val?.pageImgInAudit = details.pageImgInAudit;
        val?.headPortraitsUrl = details.headPortraitsUrl;
      });
    } else {
      debugPrint("res.result 不是有效的 JSON 数据");
    }
  }

  getCountryList() async {
    var response = await HttpHelper.instance().post(
      HttpApi.getcountry,
      showLoading: true,
      showToast: true,
    );
    if (response.isSuccess && response.result is Map<String, dynamic>) {
      List<dynamic> tmpDataList = response.result['items'] ?? [];
      List<CountryModel> dataList = tmpDataList
          .whereType<Map<String, dynamic>>() // 确保元素是 Map 类型
          .map((element) => CountryModel.fromJson(element)) // 转换为 CountryModel
          .toList(); // 转换为 List
      countryList.value = dataList; // 更新 countryList
    }
  }

  getTagList() async {
    var response = await HttpHelper.instance().post(
      MeApi.userTags,
      showLoading: true,
      showToast: true,
    );
    if (response.isSuccess && response.result is List<dynamic>) {
      List<dynamic> tagsJson = response.result;
      List<LableModel> tags = tagsJson
          .whereType<Map<String, dynamic>>() // 确保元素是 Map 类型
          .map((element) => LableModel.fromJson(element)) // 转换为 TagsModel
          .toList();
      tagList.value = tags;
    }
  }

  getUserDynamic(String userId) async {
    var res = await HttpHelper.instance().post(
      MeApi.userDynamic,
      body: {"userId": userId},
      showLoading: true,
      showToast: true,
    );
    if (res.result is Map<String, dynamic>) {
    } else {
      debugPrint("res.result 不是有效的 JSON 数据");
    }
  }

  isAttention(String userId, bool isAttention) async {
    var res = await HttpHelper.instance().post(
      MeApi.isAttention,
      body: {"toUserId": userId, "isAttention": isAttention ? "0" : "1"},
      showLoading: true,
      showToast: true,
    );
    if (res.isSuccess) {
      user.update((val) {
        val?.isAttention = !isAttention;
      });
    }
    if (res.result is Map<String, dynamic>) {
    } else {
      debugPrint("res.result 不是有效的 JSON 数据");
    }
  }

  Future<String> uploadFile(
      File file, String type, String key, int seconds) async {
    var res = await HttpHelper.instance().uploadFile(file, type);
    if (res.isSuccess) {
      if (type == "audio") {
        return await uploadVoice(res.result, seconds)
            ? "Successfully updated"
            : "Update failed";
      } else {
        return await uploadUser(key, res.result);
      }
    } else {
      return "";
    }
  }

  Future<String> uploadUser(String key, String value) async {
    var res = await HttpHelper.instance().post(
      MeApi.uploadUserData,
      body: {key: value},
      showLoading: true,
      showToast: true,
    );
    debugPrint("uploadUser res.result: ${res.result}");
    if (res.isSuccess) {
      if (key == "country") {
        user.update((val) {
          val?.country = value;
        });
      } else if (key == "about") {
        user.update((val) {
          val?.about = value;
        });
      } else if (key == "headPortraitsUrl") {
        user.update((val) {
          val?.headPortraitsUrl = value;
        });
      } else {
        getUserDetails1();
      }
    } else {
      debugPrint("uploadUser res.result: ${res.result}");
    }
    return res.isSuccess ? "Successfully updated" : "Update failed";
  }

  Future<bool> uploadVoice(String voicoe, int seconds) async {
    var res = await HttpHelper.instance().post(
      MeApi.uploadVoice,
      body: {"myVoice": voicoe, "duration": seconds},
      showLoading: true,
      showToast: true,
    );
    debugPrint("uploadVoice res.result: ${res.result}");
    if (res.isSuccess) {
      user.update((val) {
        val?.myVoice = voicoe;
        val?.duration = seconds;
      });
    }
    return res.isSuccess;
  }

  Future<void> deleteVoice() async {
    var res = await HttpHelper.instance().post(
      MeApi.deleteVoice,
      showLoading: true,
      showToast: true,
    );
    if (res.isSuccess) {
      user.update((val) {
        val?.myVoice = "";
        val?.duration = 0;
      });
    }
  }

  Future<bool> _requestPermission() async {
    final PermissionStatus status = await Permission.photos.request();
    return status.isGranted;
  }

  Future<String> pickAssets(BuildContext context, String key) async {
    if (!await _requestPermission()) return "";
    if (!context.mounted) return "";
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      pickerConfig: const AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image, // 仅图片
      ),
      context,
    );
    if (result != null && result.isNotEmpty) {
      final File? imageFile = await result.first.file;
      return await uploadFile(imageFile!, "image", key, 0);
    } else {
      return "";
    }
  }

  Future<bool> chargeDiamond(String virtualMoney) async {
    var res = await HttpHelper.instance().post(
      MeApi.sessionkey,
      showLoading: true,
      showToast: true,
    );
    if (res.isSuccess) {
      var res1 = await HttpHelper.instance().post(
        MeApi.chargeDiamond,
        body: {
          "sessionkey": res.result,
          "virtualMoney": "1000",
          "payment": Platform.isAndroid ? "10" : "4"
        },
        showLoading: true,
        showToast: true,
      );
      return res1.isSuccess;
    } else {
      return false;
    }
  }
}
